package ngames.com.sushitv.action;

import android.app.Activity;
import android.content.Intent;
import android.support.design.widget.TextInputLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

import ngames.com.sushitv.R;
import ngames.com.sushitv.action.countrycode.CountryCodeAction;
import ngames.com.sushitv.activity.ForgotPasswordActivity;
import ngames.com.sushitv.activity.MainActivity;
import ngames.com.sushitv.activity.RegisterActivity;
import ngames.com.sushitv.base.BaseAction;
import ngames.com.sushitv.core.ModelCallback;
import ngames.com.sushitv.entity.UserInfo;
import ngames.com.sushitv.tools.AppUtil;
import ngames.com.sushitv.tools.Constants;

/**
 * Created by Jeffrey on 2016/8/1.
 */
public class LoginAction extends BaseAction implements View.OnClickListener {
    private AutoCompleteTextView mEmailView;
    private EditText mPasswordView;
    private EditText mPhoneEdt;
    private TextInputLayout mEmailTil;
    private RelativeLayout mPhoneLayout;
    private FBLoginAction mFBLoginAction;
    private String mLoginType;
    CountryCodeAction mCountryCodeAction;

    public LoginAction(Activity activity, View baseView) {
        super(activity, baseView);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        View baseView = mBaseView;
        mEmailView = (AutoCompleteTextView) baseView.findViewById(R.id.email);
        populateAutoComplete();

        mPhoneEdt = (EditText) baseView.findViewById(R.id.pr_edt_phone);
        mPasswordView = (EditText) baseView.findViewById(R.id.password);
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        Button emailSignInButton = (Button) baseView.findViewById(R.id.email_sign_in_button);
        emailSignInButton.setOnClickListener(this);

        baseView.findViewById(R.id.txv_forgot).setOnClickListener(this);
        baseView.findViewById(R.id.btn_fb_login).setOnClickListener(this);
        baseView.findViewById(R.id.btn_sign_up).setOnClickListener(this);

        mEmailTil = (TextInputLayout) baseView.findViewById(R.id.til_email);
        mPhoneLayout = (RelativeLayout) baseView.findViewById(R.id.phone_layout);
        mPhoneLayout.setVisibility(View.GONE);

        mLoginType = Constants.LOGIN_TYPE_EMAIL;
        RadioGroup titleButton = (RadioGroup) findViewById(R.id.rdg_title_bar);
        titleButton.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rbt_email:
                        mLoginType = Constants.LOGIN_TYPE_EMAIL;
                        mEmailTil.setVisibility(View.VISIBLE);
                        mEmailView.requestFocus();
                        mPhoneLayout.setVisibility(View.GONE);
                        mEmailView.setSelection(mEmailView.getText().length());
                        break;
                    case R.id.rbt_phone:
                        mLoginType = Constants.LOGIN_TYPE_PHONE;
                        mEmailTil.setVisibility(View.GONE);
                        mPhoneLayout.setVisibility(View.VISIBLE);
                        mPhoneEdt.requestFocus();
                        mPhoneEdt.setSelection(mPhoneEdt.getText().length());
                        break;
                }
            }
        });

        mFBLoginAction = new FBLoginAction(mActivity, mBaseView);
        mFBLoginAction.onCreate();

        mCountryCodeAction = new CountryCodeAction(mActivity, mPhoneLayout);
        mCountryCodeAction.onCreate();

        mEmailView.setText("nick2@test2.com");
        mPhoneEdt.setText("13888888888");
        mPasswordView.setText("123456");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mFBLoginAction.onDestroy();
        mCountryCodeAction.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mFBLoginAction.onActivityResult(requestCode, resultCode, data);
        mCountryCodeAction.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.email_sign_in_button:
                attemptLogin();
                break;
            case R.id.txv_forgot:
                mActivity.startActivity(new Intent(mActivity, ForgotPasswordActivity.class));
                break;
            case R.id.btn_fb_login:
                mFBLoginAction.loginFB();
                break;
            case R.id.btn_sign_up:
                RegisterActivity.goRegisterActivity(mActivity, Constants.ACCOUNT_TYPE_APP);
                break;
        }
    }

    private void populateAutoComplete() {

    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        // Reset errors.
        mEmailView.setError(null);
        mPhoneEdt.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String countryCode = mCountryCodeAction.getCountryCode();
        String phone = mPhoneEdt.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        if (Constants.LOGIN_TYPE_EMAIL.equals(mLoginType) && TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (Constants.LOGIN_TYPE_EMAIL.equals(mLoginType) && !AppUtil.isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        } else if (Constants.LOGIN_TYPE_PHONE.equals(mLoginType) && TextUtils.isEmpty(countryCode)) {
            mPhoneEdt.setError("chose country code");
            focusView = mPhoneEdt;
            cancel = true;
        } else if (Constants.LOGIN_TYPE_PHONE.equals(mLoginType) && TextUtils.isEmpty(phone)) {
            mPhoneEdt.setError("input phone");
            focusView = mPhoneEdt;
            cancel = true;
        } else if (TextUtils.isEmpty(password)) {
            mPasswordView.setError(getString(R.string.enter_password));
            focusView = mPasswordView;
            cancel = true;
        } else if (!AppUtil.isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            login(mLoginType, email, countryCode, phone, password);
        }
    }

    private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
        //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
        ArrayAdapter<String> adapter =
                new ArrayAdapter<>(mActivity, android.R.layout.simple_dropdown_item_1line, emailAddressCollection);

        mEmailView.setAdapter(adapter);
    }

    private void login(String type, String email, String area, String phone, String password) {
        getAppModel().getUserService().login(type, email, area, phone, password, new ModelCallback<UserInfo>() {
            @Override
            public void onBeforeRequest(String urlTag) {

            }

            @Override
            public void onSuccess(UserInfo data) {
                showProgress(false);
                mActivity.startActivity(new Intent(mActivity, MainActivity.class));
                mActivity.finish();
            }

            @Override
            public void onFailure(String errorEvent, String message) {
                showProgress(false);
                Toast.makeText(getAppApplication(), errorEvent, Toast.LENGTH_SHORT).show();
                if ("3311".equals(errorEvent)) {
                    mEmailView.setError("account not exist");
                    mEmailView.requestFocus();
                    Toast.makeText(getAppApplication(), "account not exist", Toast.LENGTH_SHORT).show();
                } else if ("3312".equals(errorEvent)) {
                    mPhoneEdt.setError("error");
                    mPhoneEdt.requestFocus();
                } else if ("3313".equals(errorEvent)) {
                    mEmailView.setError("email not been verified");
                    mEmailView.requestFocus();
                } else {
                    Toast.makeText(getAppApplication(), "login error", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
